package org.NooLab.glue.net.sockets.udp;

   

import java.net.SocketException;

import org.NooLab.glue.components.DataSenderIntf;



public class UdpDataSender implements DataSenderIntf{
	
	private static final long serialVersionUID = -7479481270330284370L;

	 
	
	// This is the port we are sending to
	int clientPort = 9100; // video data
	int ctrlPort   = 9101; // control data in XML format
	String ip_address = "localhost" ;
	
	UdpObjects udphandler ;
	
	int timeoutValue = 0;
	int lastSenderState=0;
	

	public UdpDataSender( int clientport, int ctrlport){
		
		clientPort = clientport ;
		ctrlPort = ctrlport ;
		
		
		
		udphandler = new UdpObjects( clientPort, ip_address);
		 
		try {

			udphandler.dsocketOut.setSoTimeout(timeoutValue) ;
		
		} catch (SocketException e) {
			e.printStackTrace();
		}
		
		// serving several machines would be possible too...
		// udpvideo = new UdpVideo(clientPort, ip_address, ip_address2, ip_address3);
		// instead of <udpvideo.broadcast(myCapture)> one would use <udpvideo.broadcastAll(myCapture)>
		 
	   
	}

	public void setTimeOut( int value){
		
		timeoutValue = value ;
		if (udphandler!=null){
			
			try {
			
				udphandler.dsocketOut.setSoTimeout(timeoutValue) ;

			} catch (SocketException e) {
				e.printStackTrace();
			}
		}
		
	}
	
	public void release(){
		udphandler.close() ;
	}
	
	@Override
	public void send(Object obj) {
	 
		send(obj,"");
	}

	public void send( Object obj, String suid ){
		
		byte[] data;
		int result = -1 ;
		
		try {
		
			// data = getBytesFromObject(obj) ;
		 
			udphandler.broadcast( obj );
			
			result = udphandler.getLastState();
			
		} catch (Exception e) {
			lastSenderState = __SEND_ERR_ERROR;
			
			// if (stopOnError) e.printStackTrace();
			String str="";
			if (suid.length()>0){
				str = "(sending uid="+suid+")";
			}
			System.err.println("Critical error in UDP sending "+str+": "+e.getMessage() );
		}
	
		return  ;
	}


	@Override
	public int getLastState(String suid) {
		 
		return lastSenderState;
	}


}
